package com.quxing.amazon.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quxing.amazon.mapper.CategoryMapper;
import com.quxing.amazon.model.Category;
import com.quxing.amazon.service.CategoryService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 亚马逊商品分类 服务实现类
 * </p>
 *
 * @author zhb
 * @since 2021-05-09
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    @Cacheable(cacheNames = "category", key = "'trees'")
    public List<Tree<Integer>> trees() {
        List<Category> categories = this.list();
        List<TreeNode<Integer>> treeNodes = categories.stream()
                .map(category -> new TreeNode<Integer>().setId(category.getId())
                        .setName(category.getName())
                        .setParentId(category.getParentId()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodes);
    }


    @Override
    public List<Integer> getAllChildrenIdsByCategoryId(Integer categoryId, List<Integer> result) {
        List<Category> categories = this.list();
        List<Integer> collect = categories.stream()
                .filter(category -> category.getParentId().equals(categoryId))
                .map(Category::getId)
                .collect(Collectors.toList());
        if (collect.size() == 0) {
            result.add(categoryId);
        } else {
            for (Integer integer : collect) {
                this.getAllChildrenIdsByCategoryId(integer, result);
            }
        }
        return result;
    }

    @Override
    public List<Category> listByParentId(Integer parentId) {
        LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery().eq(Category::getParentId, parentId);
        return this.list(wrapper);
    }

}
